package encaps.action;

import encaps.entities.Grant;
import encaps.entities.Role;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Labels;
import encaps.utils.EntityUtil;
import encaps.utils.Provider;
import encaps.utils.RoleGrantGenreEnum;
import encaps.utils.XMLHelper;
import java.util.Date;
import org.jdom.Element;

public class CreateRoleAction extends ShowEmptyRolePageAction {

    public static final String CREATE_ROLE = "createRole";

    public CreateRoleAction(ActionContext context, Grant requiredGrant) {
        super(context, requiredGrant);
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            String name, grants;
            name = actionContext.getTextParameter(NAME);
            grants = actionContext.getTextParameter(GRANTS);
            if (name != null) {
                Role role = new Role(name);
                String[] g = grants.split(";");
                for (String grant : g) {
                    if (Provider.isExist(RoleGrantGenreEnum.GRANT, grant)) {
                        Grant gr = new Grant(grant);
                        role.addGrant(gr);
                    }
                }
                Provider.createRole(role);
            }
            JMSUtil.sendLogMessage(Log.INSERT,
                    EntityUtil.getUserHome().findByLogin(actionContext.getUserLogin()).getID(),
                    actionContext.getUserLogin(), new Date(), Role.TABLE_NAME,
                    null, name);
            return XMLHelper.createTextMessage(Labels.getLabel(Labels.ROLE_CREATED));

        } catch (Exception ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        }
    }
}